//配置路由的地方
import VueRouter from "vue-router"
import Vue from "vue"
import routes from "./routes"

import store from "@/store"

// vue使用插件
Vue.use(VueRouter);

// push和replace重写
// console.log(VueRouter.prototype)
let originPush = VueRouter.prototype.push
let originReplace = VueRouter.prototype.replace

VueRouter.prototype.push = function (location, reslove, reject) {
    if (reslove && reject) {
        originPush.call(this, location, reslove, reject);
    } else {
        originPush.call(this, location, () => {}, () => {});
    }
}

VueRouter.prototype.replace = function (location, reslove, reject) {
    if (reslove && reject) {
        originReplace.call(this, location, reslove, reject);
    } else {
        originReplace.call(this, location, () => {}, () => {});
    }
}

// 配置路由
let router = new VueRouter({
    routes,
    scrollBehavior(to, from, savedPosition) {
        // 始终滚动到顶部
        return {
            y: 0
        }
    },
})

// 全局前置守卫
// to: 即将要进入的目标; from: 当前导航正要离开的路由
// next(): 放行； next(path)跳转到path
router.beforeEach(async (to, from, next) => {
    // 获取token
    let token = store.state.user.token;
    // 获取用户信息，如果只获取userInfo，返回永远是对象。空对象也是true
    let name = store.state.user.userInfo.name;
    if (token) {
        if (to.path == "/login" || to.path == "/register") {
            next('/home')
        } else {
            if(name){
                next();
            }else{
                try {
                    await store.dispatch("getUserInfo")
                    next()
                } catch (error) {
                    // token验证失效，需重新登录；退出登录
                    await store.dispatch("userLogout");
                    next()
                }
            }
        }
    } else {
        // 未登录不能跳转到（trade, pay，paysuccess，center）等页面。
        let toPath = to.path;
        if(toPath.indexOf("/center/myorder") != -1 || toPath.indexOf("/pay") != -1 || toPath.indexOf("/trade") != -1){
            next('/login?redirect=' + toPath);
        }else{
            next();
        }
    }
})

export default router;
